package com.demo.commons.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;

import com.demo.commons.constants.BaseConst;

/**
 * 设置公共参数 Filter
 * 1、BaseURL---->http://localhost:8080
 * 2、ctx---->request.contextPath
 * 3、currentURL---->当前地址
 * <p>User: 杨浩泉
 * <p>Date: 2015年9月14日
 * <p>Version: 1.0
 */
public class CommonDataFilter implements Filter {

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		
		
		if (request.getAttribute(BaseConst.BASE_URL) == null) {
			request.setAttribute(BaseConst.BASE_URL, getBasePath(request));
		}
		if (request.getAttribute(BaseConst.CONTEXT_PATH) == null) {
            request.setAttribute(BaseConst.CONTEXT_PATH, request.getContextPath());
        }
        if (request.getAttribute(BaseConst.CURRENT_URL) == null) {
            request.setAttribute(BaseConst.CURRENT_URL, extractCurrentURL(request, true));
        }
        if (request.getAttribute(BaseConst.NO_QUERYSTRING_CURRENT_URL) == null) {
            request.setAttribute(BaseConst.NO_QUERYSTRING_CURRENT_URL, extractCurrentURL(request, false));
        }
        if (request.getAttribute(BaseConst.BACK_URL) == null) {
            request.setAttribute(BaseConst.BACK_URL, extractBackURL(request));
        }
        
        chain.doFilter(request, response);
        return;
	}
	
	/**
	 * 当前访问URL
	 * @param request
	 * @param needQueryString
	 * @return
	 */
	private String extractCurrentURL(HttpServletRequest request, boolean needQueryString) {
        String url = request.getRequestURI();
        String queryString = request.getQueryString();
        if (!StringUtils.isEmpty(queryString)) {
            queryString = "?" + queryString;
            if (queryString.startsWith("&")) {
                queryString = "?" + queryString.substring(1);
            }
        }
        if (!StringUtils.isEmpty(queryString) && needQueryString) {
            url = url + queryString;
        }
        return getBasePath(request) + url;
    }

    /**
     * 上一次请求的地址
     * 1、先从request.parameter中查找BackURL
     * 2、获取header中的 referer
     *
     * @param request
     * @return
     */
    private String extractBackURL(HttpServletRequest request) {
        String url = request.getParameter(BaseConst.BACK_URL);
        if (StringUtils.isEmpty(url)) {
            url = request.getHeader("Referer");
        }
        if(!StringUtils.isEmpty(url) && (url.startsWith("http://") || url.startsWith("https://"))) {
            return url;
        }
        if (!StringUtils.isEmpty(url) && url.startsWith(request.getContextPath())) {
            url = getBasePath(request) + url;
        }
        return url;
    }
    
    private String getBasePath(HttpServletRequest req) {
        StringBuffer baseUrl = new StringBuffer();
        String scheme = req.getScheme();
        int port = req.getServerPort();

        baseUrl.append(scheme);        
        baseUrl.append("://");
        baseUrl.append(req.getServerName());
        if ((scheme.equals("http") && port != 80) || (scheme.equals("https") && port != 443)) {
            baseUrl.append(':');
            baseUrl.append(req.getServerPort());
        }
        return baseUrl.toString();
    }
    
    
    @Override
	public void init(FilterConfig filterConfig) throws ServletException {}

	@Override
	public void destroy() {}

}
